package com.uinnova.product.eam.workable.listener;

import com.uinnova.product.eam.workable.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.history.HistoricProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Component("publicAccessUserInfoListener")
public class PublicAccessUserInfoListener implements ExecutionListener {

    @Resource
    private RestTemplate restTemplate;

    @Value("${generic.user.url}")
    private String genericUserUrl;

    @Autowired
    private transient RuntimeService runtimeService;

    @Autowired
    private transient HistoryService historyService;

    @Resource
    private HttpUtil httpUtil;

    @Override
    public void notify(DelegateExecution execution) {
        //获取当前任务的id
        FlowElement currentFlowElement = execution.getCurrentFlowElement();
        String taskDefinitionId = currentFlowElement.getDocumentation();
        log.info("当前任务定义id：{}", taskDefinitionId);
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(execution.getProcessInstanceId())
                .singleResult();
        //获取流程定义id
        String splitProcessDefinitionId = historicProcessInstance.getProcessDefinitionKey();
        log.info("当前流程定义id：{}", splitProcessDefinitionId);
        //获取当前流程实例业务主键
        String processInstanceBusinessKey = execution.getProcessInstanceBusinessKey();
        log.info("当前流程业务主键：{}", processInstanceBusinessKey);
        //TODO 远程调用eam获取不同节点不同人员审批的人员信息 genericUserUrl需要加入到白名单
        String requestUrl = genericUserUrl+"?defKey="+splitProcessDefinitionId+"&businessKey="+processInstanceBusinessKey+"&taskKey="+taskDefinitionId;
        log.info("获取通用审批用户请求的url:{}",requestUrl);
        List<String> userLoginCodes = httpUtil.get(requestUrl, List.class);
        log.info("获取审批用户列表:{}",userLoginCodes);
        Map<String, Object> variables = execution.getVariables();
        if (!CollectionUtils.isEmpty(userLoginCodes)) {
            log.info("审批用户：{}", userLoginCodes);
            String currentActivityId = execution.getCurrentActivityId();
            log.info("执行器id{}", currentActivityId);
            variables.put("assigneeList", userLoginCodes);
        }
        execution.setVariables(variables);
    }
}
